﻿using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using QuanLyHopDong.Biz.Model;

namespace QuanLyHopDong.Biz
{
    public class PhieuXuatKhoBiz
    {
        public List<PhieuXuatKho> GetPhieuXuatKhos(int hopDongId)
        {
            using (var db = new HopDongEntities())
            {
                return db.PhieuXuatKhoes.Where(x => x.HopDongId == hopDongId).ToList();
            }
        } 

        public void CreatePhieuXuat(PhieuXuatKho phieuXuatKho)
        {
            if (phieuXuatKho == null)
                return;
            if (string.IsNullOrWhiteSpace(phieuXuatKho.SoPhieu))
                return;

            using (var db = new HopDongEntities())
            {
                db.PhieuXuatKhoes.Add(phieuXuatKho);
                db.SaveChanges();
            }
        }

        public void DeletPhieuXuatKho(int id)
        {
            using (var db = new HopDongEntities())
            {
                db.DeletePhieuXuatKho(id);
            }
        }

        public List<PhieuXuatKho> PhieuXuatKhoList(int hopDongId)
        {
            using (var db = new HopDongEntities())
            {
                return db.PhieuXuatKhoes.Where(x => x.HopDongId == hopDongId).ToList();
            }
        }

        public PhieuXuatKho GetById(int id)
        {
            using (var db = new HopDongEntities())
            {
                return db.PhieuXuatKhoes.FirstOrDefault(x => x.Id == id);
            }
        }

        public void DeleteFilePhieuXuatKho(string filePath, int id)
        {
            File.Delete(filePath);

            using (var db = new HopDongEntities())
            {
                db.DeleteFilePhieuXuatKho(id);
            }
        }

        public void DeleteFileBienBanBanGiao(string filePath, int id)
        {
            File.Delete(filePath);

            using (var db = new HopDongEntities())
            {
                db.DeleteFileBienBanBanGiao(id);
            }
        }

        public void Update(PhieuXuatKho phieuXuatKho)
        {
            if (phieuXuatKho == null)
                return;
            if (phieuXuatKho.Id < 0)
                return;
            if (string.IsNullOrWhiteSpace(phieuXuatKho.SoPhieu))
                return;

            using (var db = new HopDongEntities())
            {
                db.PhieuXuatKhoes.Attach(phieuXuatKho);
                db.Entry(phieuXuatKho).State = EntityState.Modified;
                db.SaveChanges();
            }
        }
    }
}
